<template>
  <div>
    <!-- 表格的标题加按钮 -->
    <div class="bg-#fff dark:bg-#141414 b-rd-8 p-24 mb-24">
      <vxe-toolbar
        ref="toolbarRef"
        class="flex items-center justify-between mb-16 py-0"
      >
        <template #buttons>
          <!-- 按钮样式的文件选择器 -->
          <el-button
            class="text-14 font-600! h-32 mr-4"
            type="primary"
            @click="handleImportButtonClick"
          >
            导入文件
            <!-- 隐藏的原生输入框 -->
            <input
              ref="fileInput"
              type="file"
              accept=".xlsx,.xls"
              @change="handleFileSelect"
              style="display: none"
            />
          </el-button>
          <!-- 现有导出按钮 -->
          <el-button
            class="text-14 font-600! h-32"
            :icon="Plus"
            @click="exportToExcel"
            type="primary"
            >导出</el-button
          >
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="tableRef"
        :column-config="columnConfig"
        round
        show-overflow
        sync-resize
        auto-resize
        max-height="600"
        border="inner"
        :data="tableData"
      >
        <vxe-column type="checkbox" title="" width="50"></vxe-column>
        <vxe-column field="name" title="姓名" min-width="100"></vxe-column>
        <vxe-column field="age" title="年龄" min-width="100"></vxe-column>
        <vxe-column field="sex" title="性别" min-width="100"></vxe-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </vxe-table>
    </div>
    <div>{{ num }}</div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted, onUnmounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import * as XLSX from "xlsx";
import { ElMessage } from "element-plus";
const { emitter } = getCurrentInstance().appContext.config.globalProperties;
import { useCounterStore } from "../store/counter.js";
const counterStore = useCounterStore();
onMounted(() => {
    emitter.on("resize", (size) => {
      handleClick();      
    });
});
const tableData = ref([
  {
    name: "张三",
    age: "20",
    sex: "male",
  },
]); // 表格数据
const num = ref(parseInt(localStorage.getItem("count")));
const flag = ref(true);

const handleClick = () => {
  num.value+=1;
  localStorage.setItem("count", num.value);
  console.log("num.value :>> ", num.value)
};

const columnConfig = reactive({
  maxFixedSize: 0,
  resizable: true,
});
// 导出表格数据到Excel
const exportToExcel = () => {
  const worksheet = XLSX.utils.json_to_sheet(tableData.value);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  XLSX.writeFile(workbook, "table_data.xlsx");
};

// 新增：处理文件选择
const handleFileSelect = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 校验类型（同方案一）
  const validTypes = [
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel",
  ];
  if (!validTypes.includes(file.type)) {
    ElMessage.error("仅支持 .xlsx 或 .xls 文件");
    return;
  }

  // 读取并解析文件（同方案一）
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const parsedData = XLSX.utils.sheet_to_json(worksheet);
      tableData.value = parsedData;
      ElMessage.success("数据导入成功");
      console.log("tableData.value :>> ", tableData.value);
    } catch (err) {
      ElMessage.error("文件解析失败，请检查格式");
    }
  };
  reader.readAsArrayBuffer(file);
};

// 新增：获取隐藏输入框的 DOM 引用
const fileInput = ref(null);

// 新增：按钮点击时触发文件选择
const handleImportButtonClick = () => {
  fileInput.value?.click(); // 触发隐藏输入框的点击事件
};
</script>
